//
//  M4HtmlWebViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/7.
//

import UIKit
import WebKit
import SafariServices

class M4HtmlWebViewController: M4BaseViewController, WKNavigationDelegate, WKUIDelegate {
    
    var M4WebUrl: String = ""
    var M4WebTitle: String = ""
    private var M4StratTime: Int = 0
    var M4OpenPrivacy: Bool = false
    private var M4WebView: WKWebView!
    var M4FormLimit: Bool = false
    var M4LimitBlock: (() -> Void)?
//    var M4OpenRepayCode: Bool = false
//    var M4RepayParam: [String : Any] = [:]
    
    let loading = M4LoadingAlertView()
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if M4OpenPrivacy {
            M4DeviceDataManager.m4DeviceShare.m4EPS = Int(Date().timeIntervalSince1970) - M4StratTime
            print("============================")
            print(M4DeviceDataManager.m4DeviceShare.m4EPS)
            print("============================")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        M4NavTitle(M4Title: M4WebTitle)
        M4_layoutViews()
        if M4OpenPrivacy {
            M4StratTime = Int(Date().timeIntervalSince1970)
            M4DeviceDataManager.m4DeviceShare.m4CVQs += 1
        }
        
    }
    
    override func M4BackClick(sender: UIButton) {
        if M4FormLimit {
            M4LimitBlock?()
            self.navigationController?.popViewController(animated: true)
        }
        else {
            if (self.presentingViewController != nil && self.navigationController?.viewControllers.count == 1) {
                self.dismiss(animated: true)
            } else {
                self.navigationController?.popViewController(animated: true)
            }
            sender.M4EventUnavailable = false
        }
    }
    
    private func M4_layoutViews() {
        M4WebView = WKWebView.init(frame: CGRect(x: 0, y: M4NavigationFullHeight(), width: M4ScreenWidth, height: M4ScreenHeight-M4NavigationFullHeight()-M4SafeDistanceBottom()), configuration: M4WebConfig)
        self.view.addSubview(M4WebView)
        M4WebView.navigationDelegate = self
        M4WebView.uiDelegate = self
        M4WebView.scrollView.showsHorizontalScrollIndicator = false
        M4WebView.scrollView.showsVerticalScrollIndicator = false
        M4WebUrl = M4WebUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
//        M4WebUrl =  M4WebUrl.replacingOccurrences(of: "http://", with: "")
//        M4WebUrl = M4WebUrl.replacingOccurrences(of: "https://", with: "")
        let s = M4WebUrl.prefix(4)
        if s != "http" {
            M4WebUrl = "https://" + M4WebUrl
        }
        let request = URLRequest.init(url: URL.init(string: M4WebUrl)!)
        
        loading.M4LoadingAlertShow()
        
        let dataStore = WKWebsiteDataStore.default()
        dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), completionHandler: { (records) in
            for record in records{
                
                WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {
                    print("清除成功\(record)")
                })
            }
        })
        M4WebView.load(request)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        loading.M4AlertViewHidden()
    }
    
//    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        print("Decide policy called for URL: \(navigationAction.request.url?.absoluteString ?? "")")
//        decisionHandler(.allow)
//    }
//    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if let url = URL(string: navigationAction.request.url?.absoluteString ?? "") {
            let safariController = SFSafariViewController(url: url)
            present(safariController, animated: true)
        }
        return nil
    }
    
    lazy private var M4WebConfig: WKWebViewConfiguration = {
//        let userContent = WKUserContentController()
//        userContent.add(self, name: "toastMessage")
//        userContent.add(self, name: "backUpPage")
//        userContent.add(self, name: "Displayloading")
//        userContent.add(self, name: "hideloadding")
        let config = WKWebViewConfiguration()
//        config.selectionGranularity = .dynamic
        config.mediaTypesRequiringUserActionForPlayback = .all
        config.allowsInlineMediaPlayback = true
//        config.userContentController = userContent
        let preference = WKPreferences()
        preference.javaScriptCanOpenWindowsAutomatically = true
        config.preferences = preference
        return config
    }()

}

//extension M4HtmlWebViewController {
//
//    private func M4_hiddenNetwork() {
//        M4PublicRequest.M4_hiddenSwitchNetwork { _ in
//            DispatchQueue.main.async {
//                if !M4UserInfoManager.M4_userShare.M4_auditAccount {
//                    M4PublicInfoManager.M4_uploadDataValidNoAlert { _ in }
//                }
//            }
//        }
//    }
//    
//    private func M4RepayCodeNetwork() {
//        M4NetworkManager().M4Request(M4NetworkTarget.M4TargetType(.M4RepayCode, params: M4RepayParam)) { result in
//            if result.code == 1 {
//                let data = result.data as? [String : Any]
//                let type = data?["bwzFKLtHMxG8L"] as? Int
//                let url = type == 1 ? data?["yuBIGd"] as? String : data?["vPB7uKuCm9"] as? String
//                self.M4WebUrl = url ?? ""
//                self.M4_layoutViews()
//            }
//            else {
//                M4Toast.showInfoToast(info: result.msg ?? "")
//            }
//        }
//    }
//}
